package com.util;

import cn.hutool.core.codec.Base64;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class IconUtil {

    public static String icon(BufferedImage in , float quality , int size) throws Exception {
//        if(quality - 0.05f < 0) {
//            return  ;
//        }
        ByteArrayOutputStream out = new ByteArrayOutputStream() ;
        Thumbnails.of(in).size(150 , 300).outputFormat("JPG").outputQuality(quality).keepAspectRatio(true).toOutputStream(out) ;
        byte[] arr = out.toByteArray() ;
        String base64 = Base64.encode(arr) ;
        out.close();
        if(base64.length() > size) {
            return icon(in , quality - 0.1f, size) ;
        }else{
            BufferedImage img = ImageIO.read(new ByteArrayInputStream(arr)) ;
            return base64 ;
        }
    }

    public static void main(String[] args) throws Exception {
        BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\lenovo\\Desktop\\IMG_20210420_172921.jpg")) ;
        String base64 = icon(image , 0.6f  , 1024*5) ;
        ByteArrayInputStream in = new ByteArrayInputStream(Base64.decode(base64)) ;
        BufferedImage img = ImageIO.read(in) ;
        ImageIO.write(img , "JPG" , new File("./icon.png")) ;
    }
}
